﻿// Allows the component to be highlighted on mouseover event
define([
'Xjs/core/util',
// Ensure the creation of the global Xjs
'Xjs/app'
],
function (util) {
    'use strict';

    var type = 'selectable', // Use the type registration to avoid recreating the type
    Selectable = Xjs.getType(type);

    if (Selectable) { // It has been already loaded
        return Selectable;
    }

    // Renders the html from a component
    Selectable = util.define({

        type: type, // Set the type

        initialize: function (conf) {

            conf = conf || {};

            this.selectable = conf.selectable || this.selectable;
            this.selectedCls = conf.selectedCls || this.selectedCls || 'w-selected';
            this.onSelect = conf.onSelect || this.onSelect;
            this.onDeselect = conf.onDeselect || this.onDeselect;

            if (this.selectable) {
                this.enableSelectable(conf);
            }
        },

        enableSelectable: function (conf) {

            var me = this;
            me.selectable = true;

            me.addClass('w-selectable');

            // Register the events
            me.addHandler('onRender', function () {

                if (me.selected) { // Initially selected
                    me.select(); // Set this control as selected
                }

                me.on('click', function (evt) {

                    evt.stopPropagation();

                    me.select(); // Set this control as selected
                });
            });
        },

        select: function () {

            if (!this.selectable) {
                return;
            }

            if (this.selected) {
                return;
            }

            // Add the selected component to the collection of selected items of the application
            Xjs.select(this, false);

            this.selected = true;

            this.addClass(this.selectedCls);

            if (this.onSelect) {
                this.onSelect.call(this);
            }
        },

        deselect: function () {

            if (!this.selectable) {
                return;
            }

            if (!this.selected) {
                return;
            }

            this.selected = false;

            this.removeClass(this.selectedCls);

            if (this.onDeselect) {
                this.onDeselect.call(this);
            }
        }
    });

    Xjs.registerType(Selectable);

    return Selectable;
});